package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper,Sku> implements SkuService {
    @Override
    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> skus = listByIds(ids);
        return SkuDTO.convertEntityList(skus);
    }

    @Override
    public List<SkuDTO> querySkuBySpuId(Long id) {
        List<Sku> skus = query().eq("spu_id", id).list();
        return SkuDTO.convertEntityList(skus);
    }

    @Override
    @Transactional
    public void reduceSkuStock(Map<Long, Integer> map) {
        Set<Long> longs = map.keySet();
        List<Sku> skus = listByIds(longs);
        if(skus==null){
            throw new LyException(400,"您选购的商品已过期");
        }
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : map.entrySet()) {
                Map<String, Object> param = new HashMap<>();
                param.put("id",entry.getKey());
                param.put("num",entry.getValue());
                baseMapper.reduceSkuStock(param);
            }
            sqlSession.flushStatements();
        });

    }

    @Override
    public void plusSkuStock(Map<Long, Integer> map) {
        executeBatch(sqlSession -> {
            for (Map.Entry<Long, Integer> entry : map.entrySet()) {
                Map<String, Object> param = new HashMap<>();
                param.put("id",entry.getKey());
                param.put("num",entry.getValue());
                baseMapper.plusSkuStock(param);
            }
            sqlSession.flushStatements();
        });

    }
}
